<template>
  <div class="profile-page">
    <!-- 顶部背景 -->
    <div class="profile-header" :style="{ backgroundImage: `url(${userInfo.coverImage})` }">
      <div class="header-overlay">
        <div class="container">
          <div class="header-content">
            <!-- 头像 -->
            <div class="avatar-section">
              <div class="avatar-wrapper">
                <img :src="userInfo.avatar" :alt="userInfo.name" class="user-avatar" />
                <el-button
                  v-if="isOwner"
                  circle
                  class="edit-avatar-btn"
                  @click="showAvatarUpload = true"
                >
                  <el-icon><Camera /></el-icon>
                </el-button>
              </div>
            </div>

            <!-- 用户信息 -->
            <div class="user-info">
              <h1 class="user-name">{{ userInfo.name }}</h1>
              <p class="user-bio">{{ userInfo.bio || '这个人很懒，什么都没留下' }}</p>
              <div class="user-stats">
                <div class="stat-item">
                  <div class="stat-value">{{ userInfo.posts }}</div>
                  <div class="stat-label">动态</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ userInfo.guides }}</div>
                  <div class="stat-label">攻略</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ userInfo.followers }}</div>
                  <div class="stat-label">粉丝</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ userInfo.following }}</div>
                  <div class="stat-label">关注</div>
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button v-if="isOwner" @click="showEditDialog = true">
                <el-icon><Edit /></el-icon>
                编辑资料
              </el-button>
              <el-button v-if="isOwner" @click="showCoverUpload = true">
                <el-icon><Picture /></el-icon>
                更换封面
              </el-button>
              <el-button v-else type="primary">
                <el-icon><Plus /></el-icon>
                关注
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 内容区 -->
    <div class="container">
      <div class="profile-content">
        <!-- Tab 切换 -->
        <el-tabs v-model="activeTab" class="profile-tabs">
          <el-tab-pane label="动态" name="posts">
            <div class="posts-grid">
              <div
                v-for="post in posts"
                :key="post.id"
                class="post-card"
                @click="goToPost(post.id)"
              >
                <div class="post-cover">
                  <img :src="post.cover" :alt="post.title" />
                </div>
                <div class="post-info">
                  <h3 class="post-title">{{ post.title }}</h3>
                  <div class="post-meta">
                    <span><el-icon><View /></el-icon> {{ post.views }}</span>
                    <span><el-icon><ChatDotRound /></el-icon> {{ post.comments }}</span>
                    <span><el-icon><Star /></el-icon> {{ post.likes }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="攻略" name="guides">
            <div class="guides-grid">
              <div
                v-for="guide in guides"
                :key="guide.id"
                class="guide-card"
                @click="goToGuide(guide.id)"
              >
                <div class="guide-cover">
                  <img :src="guide.cover" :alt="guide.title" />
                  <span class="guide-category">{{ guide.category }}</span>
                </div>
                <div class="guide-info">
                  <h3 class="guide-title">{{ guide.title }}</h3>
                  <div class="guide-meta">
                    <span><el-icon><View /></el-icon> {{ guide.views }}</span>
                    <span><el-icon><ChatDotRound /></el-icon> {{ guide.comments }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="收藏" name="favorites">
            <div class="favorites-grid">
              <div
                v-for="item in favorites"
                :key="item.id"
                class="favorite-card"
                @click="goToItem(item)"
              >
                <div class="favorite-cover">
                  <img :src="item.cover" :alt="item.title" />
                </div>
                <div class="favorite-info">
                  <h3 class="favorite-title">{{ item.title }}</h3>
                  <div class="favorite-type">{{ item.type }}</div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="关于" name="about">
            <div class="about-section">
              <div class="about-card">
                <h3 class="about-title">个人简介</h3>
                <p class="about-text">{{ userInfo.bio || '这个人很懒，什么都没留下' }}</p>
              </div>
              <div class="about-card">
                <h3 class="about-title">旅行足迹</h3>
                <div class="travel-tags">
                  <el-tag
                    v-for="place in userInfo.travelPlaces"
                    :key="place"
                    class="travel-tag"
                  >
                    {{ place }}
                  </el-tag>
                </div>
              </div>
              <div class="about-card">
                <h3 class="about-title">加入时间</h3>
                <p class="about-text">{{ userInfo.joinDate }}</p>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑资料" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="昵称">
          <el-input v-model="editForm.name" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="个人简介">
          <el-input
            v-model="editForm.bio"
            type="textarea"
            :rows="4"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveProfile">保存</el-button>
      </template>
    </el-dialog>

    <!-- 上传头像对话框 -->
    <el-dialog v-model="showAvatarUpload" title="更换头像" width="400px">
      <el-upload
        class="avatar-uploader"
        action="#"
        :show-file-list="false"
        :before-upload="handleAvatarUpload"
        accept="image/*"
      >
        <img v-if="previewAvatar" :src="previewAvatar" class="preview-avatar" />
        <div v-else class="upload-placeholder">
          <el-icon class="upload-icon"><Plus /></el-icon>
          <div class="upload-text">点击上传头像</div>
        </div>
      </el-upload>
      <template #footer>
        <el-button @click="showAvatarUpload = false">取消</el-button>
        <el-button type="primary" @click="handleSaveAvatar">保存</el-button>
      </template>
    </el-dialog>

    <!-- 上传封面对话框 -->
    <el-dialog v-model="showCoverUpload" title="更换封面" width="600px">
      <el-upload
        class="cover-uploader"
        action="#"
        :show-file-list="false"
        :before-upload="handleCoverUpload"
        accept="image/*"
      >
        <img v-if="previewCover" :src="previewCover" class="preview-cover" />
        <div v-else class="upload-placeholder">
          <el-icon class="upload-icon"><Plus /></el-icon>
          <div class="upload-text">点击上传封面图</div>
        </div>
      </el-upload>
      <div class="upload-tip">建议尺寸：1920x400，支持 JPG、PNG 格式</div>
      <template #footer>
        <el-button @click="showCoverUpload = false">取消</el-button>
        <el-button type="primary" @click="handleSaveCover">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Camera,
  Edit,
  Picture,
  Plus,
  View,
  ChatDotRound,
  Star
} from '@element-plus/icons-vue'
// import { getUserProfile, updateUserProfile, uploadImage } from '@/api/user/index.js'

const route = useRoute()
const router = useRouter()

const activeTab = ref('posts')
const showEditDialog = ref(false)
const showAvatarUpload = ref(false)
const showCoverUpload = ref(false)
const previewAvatar = ref('')
const previewCover = ref('')

// 用户信息
const userInfo = ref({
  id: '',
  name: '旅行达人小王',
  avatar: 'https://i.pravatar.cc/150?img=11',
  coverImage: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1920&q=80',
  bio: '用镜头记录世界，用脚步丈量人生。热爱旅行，热爱摄影，热爱生活。',
  posts: 128,
  guides: 45,
  followers: 5420,
  following: 328,
  travelPlaces: ['三亚', '成都', '西藏', '丽江', '桂林', '厦门', '青海', '新疆'],
  joinDate: '2023年3月15日'
})

// 编辑表单
const editForm = ref({
  name: '',
  bio: ''
})

// 是否是本人
const isOwner = computed(() => {
  // TODO: 判断是否是当前登录用户
  return true
})

// 动态列表
const posts = ref([
  {
    id: 1,
    title: '川西秘境自驾游',
    cover: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=600&q=80',
    views: '1.2k',
    comments: 89,
    likes: 234
  },
  {
    id: 2,
    title: '三亚海滩日落',
    cover: 'https://images.unsplash.com/photo-1559827260-dc66d52bef19?w=600&q=80',
    views: '2.5k',
    comments: 156,
    likes: 567
  },
  {
    id: 3,
    title: '成都美食探店',
    cover: 'https://images.unsplash.com/photo-1555939594-58d7cb561ad1?w=600&q=80',
    views: '3.4k',
    comments: 234,
    likes: 892
  }
])

// 攻略列表
const guides = ref([
  {
    id: 1,
    title: '三亚5天4晚完美攻略',
    cover: 'https://images.unsplash.com/photo-1559827260-dc66d52bef19?w=600&q=80',
    category: '路线',
    views: '12.5k',
    comments: 328
  },
  {
    id: 2,
    title: '成都美食地图',
    cover: 'https://images.unsplash.com/photo-1555939594-58d7cb561ad1?w=600&q=80',
    category: '美食',
    views: '18.2k',
    comments: 567
  }
])

// 收藏列表
const favorites = ref([
  {
    id: 1,
    title: '西藏自驾游装备清单',
    cover: 'https://images.unsplash.com/photo-1519904981063-b0cf448d479e?w=600&q=80',
    type: '攻略'
  },
  {
    id: 2,
    title: '丽江古城住宿推荐',
    cover: 'https://images.unsplash.com/photo-1508804185872-d7badad00f7d?w=600&q=80',
    type: '攻略'
  }
])

// 加载用户资料
const loadUserProfile = async () => {
  try {
    const userId = route.params.id || 'me'
    // TODO: 调用API
    // const res = await getUserProfile(userId)
    // userInfo.value = res.data
  } catch (error) {
    console.error('加载失败:', error)
  }
}

// 保存资料
const handleSaveProfile = async () => {
  try {
    // TODO: 调用API
    // await updateUserProfile(editForm.value)
    
    userInfo.value.name = editForm.value.name
    userInfo.value.bio = editForm.value.bio
    showEditDialog.value = false
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 上传头像
const handleAvatarUpload = (file) => {
  previewAvatar.value = URL.createObjectURL(file)
  return false
}

// 保存头像
const handleSaveAvatar = async () => {
  try {
    // TODO: 上传图片并更新
    // const res = await uploadImage(file)
    // await updateUserProfile({ avatar: res.data.url })
    
    userInfo.value.avatar = previewAvatar.value
    showAvatarUpload.value = false
    previewAvatar.value = ''
    ElMessage.success('头像更新成功')
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

// 上传封面
const handleCoverUpload = (file) => {
  previewCover.value = URL.createObjectURL(file)
  return false
}

// 保存封面
const handleSaveCover = async () => {
  try {
    // TODO: 上传图片并更新
    // const res = await uploadImage(file)
    // await updateUserProfile({ coverImage: res.data.url })
    
    userInfo.value.coverImage = previewCover.value
    showCoverUpload.value = false
    previewCover.value = ''
    ElMessage.success('封面更新成功')
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

// 跳转到动态详情
const goToPost = (id) => {
  router.push(`/community/${id}`)
}

// 跳转到攻略详情
const goToGuide = (id) => {
  router.push(`/guides/${id}`)
}

// 跳转到收藏项
const goToItem = (item) => {
  if (item.type === '攻略') {
    router.push(`/guides/${item.id}`)
  } else {
    router.push(`/community/${item.id}`)
  }
}

onMounted(() => {
  loadUserProfile()
  editForm.value = {
    name: userInfo.value.name,
    bio: userInfo.value.bio
  }
})
</script>

<style scoped lang="less">
.profile-page {
  min-height: 100vh;
  background: #f5f7fa;
}

// 顶部背景
.profile-header {
  height: 450px;
  background-size: cover;
  background-position: center;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    inset: 0;
    background: inherit;
    filter: blur(20px);
    transform: scale(1.1);
  }
}

.header-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0.7) 100%);
  display: flex;
  align-items: flex-end;
  padding-bottom: 40px;
  backdrop-filter: blur(10px);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.header-content {
  display: flex;
  align-items: flex-end;
  gap: 32px;
  width: 100%;
}

// 头像
.avatar-section {
  flex-shrink: 0;

  z-index: 10;
}

.avatar-wrapper {
  position: relative;
  width: 180px;
  height: 180px;
}

.user-avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 8px solid #fff;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  transition: transform 0.3s;

  &:hover {
    transform: scale(1.05);
  }
}

.edit-avatar-btn {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: #fff;
  color: #ff6b6b;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

  &:hover {
    background: #ff6b6b;
    color: #fff;
  }
}

// 用户信息
.user-info {
  flex: 1;
  color: #fff;
}

.user-name {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 12px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.user-bio {
  font-size: 16px;
  margin: 0 0 20px 0;
  opacity: 0.95;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.user-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;

  .stat-value {
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 4px;
  }

  .stat-label {
    font-size: 14px;
    opacity: 0.9;
  }
}

// 操作按钮
.action-buttons {
  display: flex;
  gap: 12px;
  flex-shrink: 0;

  .el-button {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border: none;
    color: #333;
    padding: 12px 24px;
    font-size: 15px;
    font-weight: 600;
    border-radius: 24px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

    &:hover {
      background: #fff;
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
    }
  }
}

// 内容区
.profile-content {
  margin-top: 20px;
  position: relative;
  z-index: 10;
}

.profile-tabs {
  background: #fff;
  border-radius: 20px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

  :deep(.el-tabs__header) {
    margin-bottom: 32px;
    border-bottom: 2px solid #f0f0f0;
  }

  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }

  :deep(.el-tabs__item) {
    font-size: 17px;
    font-weight: 600;
    padding: 0 24px;
    height: 50px;
    line-height: 50px;
    color: #666;

    &:hover {
      color: #ff6b6b;
    }

    &.is-active {
      color: #ff6b6b;
    }
  }

  :deep(.el-tabs__active-bar) {
    height: 3px;
    background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
    border-radius: 2px;
  }
}

// 动态网格
.posts-grid,
.guides-grid,
.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 32px 24px;
}

.post-card,
.guide-card,
.favorite-card {
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #f0f0f0;

  &:hover {
    transform: translateY(-4px);
    border-color: #ff6b6b;
  }
}

.post-cover,
.guide-cover,
.favorite-cover {
  width: 100%;
  height: 220px;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8eaed 100%);

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  }
}

.post-card:hover .post-cover img,
.guide-card:hover .guide-cover img,
.favorite-card:hover .favorite-cover img {
  transform: scale(1.1);
}

.guide-category {
  position: absolute;
  top: 12px;
  left: 12px;
  background: rgba(255, 255, 255, 0.95);
  color: #ff6b6b;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}

.post-info,
.guide-info,
.favorite-info {
  padding: 16px;
}

.post-title,
.guide-title,
.favorite-title {
  font-size: 15px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-meta,
.guide-meta {
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: #999;

  span {
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

.favorite-type {
  display: inline-block;
  padding: 4px 12px;
  background: rgba(255, 107, 107, 0.1);
  color: #ff6b6b;
  border-radius: 12px;
  font-size: 12px;
}

// 关于
.about-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.about-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 24px;
}

.about-title {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 16px 0;
}

.about-text {
  font-size: 15px;
  color: #666;
  line-height: 1.7;
  margin: 0;
}

.travel-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.travel-tag {
  font-size: 14px;
  background: rgba(255, 107, 107, 0.1);
  color: #ff6b6b;
  border: none;
}

// 上传对话框
.avatar-uploader,
.cover-uploader {
  :deep(.el-upload) {
    width: 100%;
    border: 2px dashed #ddd;
    border-radius: 12px;
    cursor: pointer;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #ff6b6b;
    }
  }
}

.avatar-uploader :deep(.el-upload) {
  height: 300px;
}

.cover-uploader :deep(.el-upload) {
  height: 250px;
}

.preview-avatar,
.preview-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;

  .upload-icon {
    font-size: 48px;
    margin-bottom: 12px;
  }

  .upload-text {
    font-size: 14px;
  }
}

.upload-tip {
  font-size: 13px;
  color: #999;
  margin-top: 12px;
  text-align: center;
}

// 响应式
@media (max-width: 1024px) {
  .posts-grid,
  .guides-grid,
  .favorites-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
}

@media (max-width: 768px) {
  .profile-header {
    height: 300px;
  }

  .header-content {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .avatar-wrapper {
    width: 120px;
    height: 120px;
  }

  .user-name {
    font-size: 24px;
  }

  .user-stats {
    justify-content: center;
  }

  .action-buttons {
    width: 100%;
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }

  .posts-grid,
  .guides-grid,
  .favorites-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 12px;
  }

  .post-cover,
  .guide-cover,
  .favorite-cover {
    height: 150px;
  }
}
</style>
